package com.ndp.fb.rdb.mongo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.ndp.fb.constant.MongoConstants;
import com.ndp.fb.mongo.api.AdGroupRetentionMongoService;
import com.ndp.fb.mongo.model.AdGroupRetention;
import com.ndp.fb.util.DateUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * ad留存服务
 * Created by jacky.cheng on 2015/10/9.
 */
@Service
public class AdGroupRetentionMongoServiceImpl extends BaseMongoServiceImpl implements AdGroupRetentionMongoService {

    @Override
    public String getTableName() {
        return MongoConstants.TABLE_NAME_ADGROUP_RETENTION;
    }


    @Override
    public AdGroupRetention findByAdGroupIdAndDay(Long adGroupId, Date day) {
        day = DateUtil.getUtcDayZero(day);
        DBObject match = new BasicDBObject();
        match.put("Day", day);
        match.put("AdGroupId", adGroupId);
        Iterator<DBObject> iterator = find(match);
        if (iterator.hasNext()) {
            return JSONObject.parseObject(JSON.toJSONString(iterator.next()), AdGroupRetention.class);
        }
        return null;
    }

    @Override
    public List<AdGroupRetention> findByAdGroupIdsAndDay(List<Long> adGroupIds, Date day) {
        day = DateUtil.getUtcDayZero(day);
        DBObject match = new BasicDBObject();
        match.put("Day", day);
        match.put("AdGroupId", new BasicDBObject("$in", adGroupIds));
        Iterator<DBObject> iterator = find(match);
        List<AdGroupRetention> result = new ArrayList<>();
        if (iterator.hasNext()) {
            AdGroupRetention retention = JSONObject.parseObject(JSON.toJSONString(iterator.next()), AdGroupRetention.class);
            result.add(retention);
        }
        return result;
    }
}
